#include "bsp.h"
#include "smurf_nbiot.h"

void nbiot_check(char* order, char* check)
{
	int time = 0;
	print3((uint8_t*)order);
	print3((uint8_t*)"\r\n");
	delay_ms(100);
	while(ReceiveStata3 != 1)
	{
		time++;			
		if(time == 1000)
		{
			time = 0;
			printf("%s",order);
			printf(" Receive ERROR\r\n");
			break;
		}
		while(strstr((char*)USART3_RX_BUF, (char*)check) == NULL)
		{
			time++;			
			if(time == 1000)
			{
				time = 0;
				printf("%s",order);
				printf(" ERROR\r\n");
				break;
			}
		}
		USART3_Clr();
	}
	printf("%s", order);
	printf(" FINISH\r\n");
}


void nbiot_init(void)
{
	nbiot_check("AT", "OK");
	nbiot_check("AT+CPSMS=0", "OK");
	nbiot_check("AT+CFUN?", "OK");
	nbiot_check("AT+CIMI", "OK");
	nbiot_check("AT+CGSN=1", "OK");
	nbiot_check("AT+CSQ", "OK");
	nbiot_check("AT+CGATT?", "OK");
	nbiot_check("AT+CEREG?", "OK");
	nbiot_check("AT+CSCON?", "OK");
	nbiot_check("AT+QMTOPEN=0,\"0bd606a90b.iot-mqtts.cn-north-4.myhuaweicloud.com\",1883", "OK");
	nbiot_check("AT+QMTCONN=0,\"6360c309ba9b5e2887d6acfb_Smurf_001_0_0_2022110205\",\"6360c309ba9b5e2887d6acfb_Smurf_001\",\"744913fddbb64661d75764840c3af7a8fabb5006a4ee61e49b5ed83f90cdef76\"", "OK");
}	

void chartoint(uint8_t num, char* b)
{
	uint8_t numc, i = 0;
	numc = num / 100;
	if(numc != 0)
	{
		b[i] = numc + 48;
		i++;
	}
	
	numc = num / 10 % 10;
	if(numc != 0)
	{
		b[i] = numc + 48;
		i++;
	}
	
	numc = num % 10;
	b[i] = numc + 48;
	
	b[++i] = '\0';
}

void nbiot_electricity(int ele)
{
	int time = 0;
	char ele_c[4] = {0};
	chartoint(ele, ele_c);
	print3((uint8_t*)"AT+QMTPUB=0,0,0,0,\"$oc/devices/6360c309ba9b5e2887d6acfb_Smurf_001/sys/properties/report\",{\"services\":[{\"service_id\":\"quantity_of_electricity\",\"properties\":{\"quantity_of_electricity\":");
	print3((uint8_t*)ele_c);
	print3((uint8_t*)"}}]}\r\n");
	delay_ms(100);
	while(ReceiveStata3 != 1)
	{
		time++;			
		if(time == 1000)
		{
			time = 0;
			printf("Electricity Receive ERROR\r\n");
			break;
		}
		while(strstr((char*)USART3_RX_BUF, "OK") == NULL)
		{
			time++;			
			if(time == 1000)
			{
				time = 0;
				printf("Electricity ERROR\r\n");
				break;
			}
		}
		USART3_Clr();
	}
	delay_ms(2000);

	printf("Electricity FINISH\r\n");
}
